package org.code.mallspringboot.controller;

import org.code.mallspringboot.dto.PmsEchoDto;
import org.code.mallspringboot.pojo.*;
import org.code.mallspringboot.service.*;
import org.code.mallspringboot.vo.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/product")
public class PmsProductController {

    @Autowired
    private PmsProductService pmsProductService;

    @Autowired
    private PmsSkuService pmsSkuService;

    @Autowired
    private PmsMemberPriceService pmsMemberPriceService;

    @Autowired
    private PmsProductFullReductionService pmsProductFullReductionService;

    @Autowired
    private PmsProductLadderService pmsProductLadderService;

    @Autowired
    private PmsProductAttributeValueService pmsProductAttributeValueService;

    @Autowired
    private CmsSubjectProductRelationService cmsSubjectProductRelationService;

    @Autowired
    private CmsPrefrenceAreaProductRelationService  cmsPrefrenceAreaProductRelationService;         //


    //查询 + 分页
    @GetMapping("/list")
    public CommonResult list(@RequestParam(value = "pageNum",defaultValue = "1") int pageNum,
                             @RequestParam(value = "pageSize",defaultValue = "5") int pageSize,
                             String keyword,Integer publishStatus,Integer verifyStatus,String productSn,
                             Integer productCategoryId,Integer brandId){

        List<PmsProduct> list = pmsProductService.selectPage(pageNum, pageSize,keyword,publishStatus,
                verifyStatus,productSn,productCategoryId,brandId);
        int total = pmsProductService.total(keyword,publishStatus,
                verifyStatus,productSn,productCategoryId,brandId);
        Map map = new HashMap();
        map.put("list" , list);
        map.put("total" , total);

        if (!map.isEmpty()){
            return CommonResult.success(map);
        }
        return CommonResult.failed("查询失败");
    }

    //修改上下架
    @PostMapping("/update/publishStatus")
    public CommonResult publishStatus(int[] ids,int publishStatus){
        boolean flag = false;
        for (int id : ids) {
            if (pmsProductService.update_publishStatus(id,publishStatus) > 0) flag = true;
        }
        if (flag){
            return CommonResult.success("修改上下架成功");
        }
        return CommonResult.failed("修改上下架失败!");
    }

    //修改新品
    @PostMapping("/update/newStatus")
    public CommonResult newStatus(int[] ids,int newStatus){
        boolean flag = false;
        for (int id : ids) {
            if (pmsProductService.update_newStatus(id,newStatus) > 0) flag = true;
        }

        if (flag) {return CommonResult.success("修改新品成功");}
        return CommonResult.failed("修改新品失败");
    }

    //修改推荐
    @PostMapping("/update/recommendStatus")
    public CommonResult recommendStatus(int[] ids,int recommendStatus){
        boolean flag = false;
        for (int id : ids) {
           if (pmsProductService.update_recommendStatus(id,recommendStatus) > 0)flag = true;
        }
        if (flag) {return CommonResult.success("修改推荐成功");}
        return CommonResult.failed("修改推荐失败");
    }

    //删除
    @PostMapping("/update/deleteStatus")
    public CommonResult deleteStatus(int[] ids,int deleteStatus){
        boolean flag = false;
        for (int id : ids) {
            if (pmsProductService.deleteStatus(id,deleteStatus) > 0)flag = true;
        }
        if (flag){
            return CommonResult.success("修改成功");
        }
        return CommonResult.failed("修改失败");
    }

    //编辑回显
    @GetMapping("/updateInfo/{id}")
    public CommonResult updateInfo(@PathVariable int id){
        PmsEchoDto pmsEchoDto = pmsProductService.selectPmsProduct(id);
        pmsEchoDto.setSkuStockList(pmsSkuService.selectByIdAndKeyword(id,null));
        pmsEchoDto.setMemberPriceList(pmsMemberPriceService.selectAll(id));
        pmsEchoDto.setProductFullReductionList(pmsProductFullReductionService.selectById(id));
        pmsEchoDto.setProductLadderList(pmsProductLadderService.selectById(id));
        pmsEchoDto.setProductAttributeValueList(pmsProductAttributeValueService.selectById(id));
        pmsEchoDto.setSubjectProductRelationList(cmsSubjectProductRelationService.selectById(id));
        pmsEchoDto.setPrefrenceAreaProductRelationList(cmsPrefrenceAreaProductRelationService.selectById(id));
        if (pmsEchoDto != null) {
            return CommonResult.success(pmsEchoDto);
        }
        return CommonResult.failed("回显失败");
    }

    //编辑提交
    @PostMapping("/update/{id}")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult update(@PathVariable int id,@RequestBody PmsEchoDto pmsEchoDto){
        pmsEchoDto.setId(id);
        boolean flag = false;
        try {
            //修改主表
            if (pmsProductService.update_submit(pmsEchoDto) > 0){

                //删除会员价格表 pms_member_price
                if (pmsMemberPriceService.delete(id) > 0){
                    for (PmsMemberPrice pmsMemberPrice : pmsEchoDto.getMemberPriceList()) {
                        pmsMemberPrice.setProductId(id);
                        if (pmsMemberPriceService.addAll(pmsMemberPrice) > 0) flag = true;
                    }
                }

                //删除 pms_product_full_reduction 表
                if (pmsProductFullReductionService.delete(id) > 0){
                    for (PmsProductFullReduction pmsProductFullReduction : pmsEchoDto.getProductFullReductionList()) {
                        pmsProductFullReduction.setProductId(id);
                        if (pmsProductFullReductionService.add(pmsProductFullReduction) > 0) flag = true;
                    }
                }

                //删除 pms_product_ladder 表
                if (pmsProductLadderService.delete(id) > 0){
                    for (PmsProductLadder pmsProductLadder : pmsEchoDto.getProductLadderList()) {
                        pmsProductLadder.setProductId(id);
                        if (pmsProductLadderService.add(pmsProductLadder) > 0) flag = true;
                    }
                }
                //删除 pms_product_attribute_value 表
                if (pmsProductAttributeValueService.delete(id) > 0){
                    for (PmsProductAttributeValue pmsProductAttributeValue : pmsEchoDto.getProductAttributeValueList()) {
                        pmsProductAttributeValue.setProductId(id);
                        if (pmsProductAttributeValueService.add(pmsProductAttributeValue) > 0) flag = true;
                    }
                }

                //删除 cms_subject_product_relation 表
//                cmsSubjectProductRelationService.delete(id);
                if (cmsSubjectProductRelationService.delete(id) > 0){
                    for (CmsSubjectProductRelation cmsSubjectProductRelation : pmsEchoDto.getSubjectProductRelationList()) {
                        cmsSubjectProductRelation.setProductId(id);
                        if (cmsSubjectProductRelationService.add(cmsSubjectProductRelation) > 0) flag = true;
                    }
                }

                //删除 cms_prefrence_area_product_relation 表
//                cmsPrefrenceAreaProductRelationService.delete(id);
                if (cmsPrefrenceAreaProductRelationService.delete(id) > 0){
                    for (CmsPrefrenceAreaProductRelation cmsPrefrenceAreaProductRelation : pmsEchoDto.getPrefrenceAreaProductRelationList()) {
                        cmsPrefrenceAreaProductRelation.setProductId(id);
                        if (cmsPrefrenceAreaProductRelationService.add(cmsPrefrenceAreaProductRelation) > 0) flag = true;
                    }
                }

                for (PmsSkuStock pmsSkuStock : pmsEchoDto.getSkuStockList()) {
                    pmsSkuStock.setProductId(id);
                    if (pmsSkuService.update(pmsSkuStock.getId(),pmsSkuStock.getSkuCode(),pmsSkuStock.getPrice(),
                            pmsSkuStock.getStock(),pmsSkuStock.getLowStock()) > 0) flag = true;
                }

            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }

        if (flag){
            return CommonResult.success("修改成功");
        }
        return CommonResult.failed("修改失败");
    }

    //添加提交
    @PostMapping("/create")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult create(@RequestBody PmsEchoDto pmsEchoDto){
        boolean flag = false;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        pmsEchoDto.setStartTime(dateFormat.format(pmsEchoDto.getPromotionStartTime()));
        pmsEchoDto.setEndTime(dateFormat.format(pmsEchoDto.getPromotionEndTime()));
        //添加主表 Product
        try {
            if (pmsProductService.add(pmsEchoDto) > 0){

                for (PmsMemberPrice pmsMemberPrice : pmsEchoDto.getMemberPriceList()) {
                    if (pmsMemberPriceService.addAll(pmsMemberPrice) > 0) flag = true;
                }

                for (PmsProductFullReduction pmsProductFullReduction : pmsEchoDto.getProductFullReductionList()) {
                    if (pmsProductFullReductionService.add(pmsProductFullReduction) > 0) flag = true;
                }

                for (PmsProductLadder pmsProductLadder : pmsEchoDto.getProductLadderList()) {
                    if (pmsProductLadderService.add(pmsProductLadder) > 0) flag = true;
                }

                for (PmsProductAttributeValue pmsProductAttributeValue : pmsEchoDto.getProductAttributeValueList()) {
                    if (pmsProductAttributeValueService.add(pmsProductAttributeValue) > 0) flag = true;
                }

                for (CmsSubjectProductRelation cmsSubjectProductRelation : pmsEchoDto.getSubjectProductRelationList()) {
                    if (cmsSubjectProductRelationService.add(cmsSubjectProductRelation) > 0) flag = true;
                }

                for (CmsPrefrenceAreaProductRelation cmsPrefrenceAreaProductRelation : pmsEchoDto.getPrefrenceAreaProductRelationList()) {
                    if (cmsPrefrenceAreaProductRelationService.add(cmsPrefrenceAreaProductRelation) > 0) flag = true;
                }

            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        if (flag){
            return CommonResult.success("添加成功");
        }
        return CommonResult.failed("添加失败");
    }
}
